package com.winnie.controller;

import com.winnie.bean.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @GetMapping("/login")
    public String login(){
        return "here is login page";
    }

    @GetMapping("/home")
    public String index(){
        return "here is home page";
    }

    @GetMapping("/unauthc")
    public String unauthc(){
        return "here is unauthc page";
    }

    /**
     * 扫描所有的shiro权限校验注解，并更新权限到数据库中
     * @return
     */
    @GetMapping("/reloadPermission")
    public ResponseEntity reloadPermission(){
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        handlerMethods.values().forEach(handlerMethod -> {
            System.out.println(handlerMethod);
            if(handlerMethod.hasMethodAnnotation(RequiresPermissions.class)){
                RequiresPermissions annotation = handlerMethod.getMethodAnnotation(RequiresPermissions.class);
                String[] value = annotation.value();
                Logical logical = annotation.logical();
                // 这里根据logical的类型和权限value去写入数据库即可。  本案例不提供实现
                log.info("权限为：{}，关系为",value,logical);
            }
        });
        return ResponseEntity.success("reload successfully!");
    }
}
